package com.rules.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;


import com.rules.admin.domain.DataType;
import com.rules.admin.domain.ValueType;
import com.rules.admin.entity.BusinessModelAttributeEntity;
import com.rules.admin.service.BusinessModelAttributeService;
import com.rules.admin.utils.ResultUtils;
import com.rules.admin.utils.TypeTransform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RequestMapping({"/businessModelAttribute"})
@Controller
public class BusinessModelAttributeController {
   private static final Logger LOGGER = LoggerFactory.getLogger(BusinessModelAttributeController.class);
   @Autowired
   private BusinessModelAttributeService businessModelAttributeService;

   @RequestMapping(
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public IPage<BusinessModelAttributeEntity> queryPage(Long businessModelId, String name, IPage<BusinessModelAttributeEntity> page) {
      return this.businessModelAttributeService.queryPage(businessModelId, name, page);
   }

   @RequestMapping(
      value = {"/list/{id}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public Map<String, Object> getList(@PathVariable("id") String id) {
      List<BusinessModelAttributeEntity> list = this.businessModelAttributeService.getModelAttributesByModelId(Long.valueOf(id));
      Iterator it = list.iterator();

      while(it.hasNext()) {
         BusinessModelAttributeEntity businessModelAttributeEntity = (BusinessModelAttributeEntity)it.next();
         if (!"".equals(businessModelAttributeEntity.getParentId()) && businessModelAttributeEntity.getParentId() != null) {
            it.remove();
         }
      }

      return ResultUtils.getSuccessResultData(list);
   }

   @RequestMapping(
      value = {"/allList/{id}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public Map<String, Object> getAllList(@PathVariable("id") String id) {
      List<BusinessModelAttributeEntity> list = this.businessModelAttributeService.getModelAttributesByModelId(Long.valueOf(id));
      return ResultUtils.getSuccessResultData(list);
   }

   @RequestMapping(
      value = {"/childList/{id}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public Map<String, Object> getChildList(@PathVariable("id") String id) {
      List<BusinessModelAttributeEntity> list = this.businessModelAttributeService.getModelAttributesByParentId(Long.valueOf(id));
      return ResultUtils.getSuccessResultData(list);
   }

   @RequestMapping(
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public Map<String, Object> addBusinessModelAttribute(@RequestBody BusinessModelAttributeEntity businessModelAttributeEntity) {
      List<BusinessModelAttributeEntity> attributes = this.businessModelAttributeService.getModelAttributesByModelId(businessModelAttributeEntity.getBusinessModelId());
      if (attributes.stream().filter((attribute) -> {
         return attribute.getAttrName().equals(businessModelAttributeEntity.getAttrName());
      }).count() > 0L) {
         return ResultUtils.getFaildResultData(new String[]{"name不能重复"});
      } else {
         this.businessModelAttributeService.save(businessModelAttributeEntity);
         return ResultUtils.getSuccessResultData();
      }
   }

   @RequestMapping(
      value = {"/{id}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public BusinessModelAttributeEntity getBusinessModelAttribute(@PathVariable("id") Long id) {
      return this.businessModelAttributeService.get(id);
   }

   @RequestMapping(
      value = {"/{id}"},
      method = {RequestMethod.PUT}
   )
   @ResponseBody
   public Map<String, Object> updateBusinessModelAttribute(@RequestBody BusinessModelAttributeEntity businessModelAttributeEntity) {
      this.businessModelAttributeService.update(businessModelAttributeEntity);
      return ResultUtils.getSuccessResultData();
   }

   @RequestMapping(
      value = {"/{id}"},
      method = {RequestMethod.DELETE}
   )
   @ResponseBody
   public Map<String, Object> deleteBusinessModelAttribute(@PathVariable("id") Long id) {
      List list = this.businessModelAttributeService.getModelAttributesByParentId(id);
      if (!list.isEmpty()) {
         return ResultUtils.getFaildResultData(new String[]{"请先删除子节点！"});
      } else {
         this.businessModelAttributeService.removeById(id);
         return ResultUtils.getSuccessResultData();
      }
   }

   @RequestMapping(
      value = {"/removeAll/{businessModelId}"},
      method = {RequestMethod.DELETE}
   )
   @ResponseBody
   public Map<String, Object> deleteAllBusinessModelAttribute(@PathVariable("businessModelId") Long businessModelId) {
      if (businessModelId == null) {
         return ResultUtils.getFaildResultData(new String[]{"传入参数有误！"});
      } else {
         this.businessModelAttributeService.deleteByBusinessModel(businessModelId);
         return ResultUtils.getSuccessResultData();
      }
   }

   @RequestMapping({"/getModelAttributes"})
   @ResponseBody
   public Map<String, Object> getModelAttributes(@RequestParam("modelId") long modelId, @RequestParam(value = "attrName",required = false) String attrName) {
      List<BusinessModelAttributeEntity> attributes = this.businessModelAttributeService.getModelAttributes(modelId, attrName);
      return ResultUtils.getSuccessResultData(attributes);
   }

   @RequestMapping(
      value = {"/addFromJson"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public Map<String, Object> create(HttpServletRequest request, HttpServletResponse response, Long modelId) {
      MultipartHttpServletRequest multipartRequest;
      try {
         multipartRequest = (MultipartHttpServletRequest)request;
      } catch (Exception var11) {
         LOGGER.error("获取传入的文件失败！", var11);
         return ResultUtils.getFaildResultData(new String[]{"导入失败，请检查数据格式！"});
      }

      MultipartFile multipartFile = multipartRequest.getFile("file");

      try {
         String jsonstr = TypeTransform.inputStream2String(multipartFile.getInputStream());
         JSONArray list = JSON.parseArray(jsonstr);
         Iterator var8 = list.iterator();

         while(var8.hasNext()) {
            Object obj = var8.next();
            JSONObject jsonObj = (JSONObject)obj;
            jsonObj.put("businessModelId", modelId);
            this.map2Data(jsonObj, modelId);
         }
      } catch (Exception var12) {
         LOGGER.error("导入失败！", var12);
         return ResultUtils.getFaildResultData(new String[]{"导入失败，请检查数据格式！"});
      }

      return ResultUtils.getSuccessResultData();
   }

   public void map2Data(JSONObject obj, Long modelId) {
      BusinessModelAttributeEntity bma = new BusinessModelAttributeEntity();
      bma.setBusinessModelId(modelId);
      bma.setAttrName(obj.get("name").toString());
      bma.setDataType(DataType.valueOf(obj.get("dataType").toString()));
      bma.setValueExpress(obj.get("valueExpress").toString());
      bma.setValueType(ValueType.valueOf(obj.get("valueType").toString()));
      bma.setIsMust(obj.getBoolean("isMust"));
      if (obj.get("parentId") != null && !"".equals(obj.get("parentId"))) {
         bma.setParentId(Long.valueOf(obj.get("parentId").toString()));
      }

      this.businessModelAttributeService.save(bma);
      if ("Object".equals(obj.get("dataType").toString()) && obj.get("children") != null) {
         List list = (List)obj.get("children");
         Iterator var5 = list.iterator();

         while(var5.hasNext()) {
            Object o = var5.next();
            JSONObject jsonObj = (JSONObject)o;
            jsonObj.put("parentId", bma.getId());
            this.map2Data(jsonObj, modelId);
         }
      }

   }
}
